﻿using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using log4net;
using Mailer.Model;
using NHibernate;
using Mailer.Model.Types;
using NHibernate.Criterion;
using System.Collections.Generic;
using System.Net;

namespace Mailer.Controllers
{
	public class Utilities
	{
		static private ILog logger = LogManager.GetLogger(typeof(Utilities));

		public static Guid GetUserID(HttpContext ctx)
		{
			if (ctx.User.Identity.IsAuthenticated)
				return GetUserID(ctx.User.Identity.Name);

			return Guid.Empty;
		}

		public static Guid GetUserID(Controller c)
		{
			if (c.Request.IsAuthenticated)
				return GetUserID(c.HttpContext.User.Identity.Name);

			return Guid.Empty;
		}

		public static Guid GetUserID(string username)
		{
			Guid userid = Guid.Empty;

			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				//	using (ISession s = SessionUtilities.GetSession())
				//	{
				IList<User> u = sess.CreateCriteria<User>().Add(Expression.Eq("Username", username)).List<User>();
				if (u.Count > 0)
					userid = u[0].ID;

				// s.Close();
				//	}
				SessionUtilities.EndSession(sess);
			}

			return userid;
		}




		public static void ApplyCustomStyling(ViewDataDictionary viewdata, Application app)
		{
			string lang = app.GetPropertyValue("language", "");
			if (!string.IsNullOrEmpty(lang))
				Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
			else
				Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");

			viewdata["userstylesheet"] = app.GetPropertyValue("userstylesheet");
			viewdata["userheadhtml"] = app.GetPropertyValue("userheadhtml");
			viewdata["usertophtml"] = app.GetPropertyValue("usertophtml");
			viewdata["userbottomhtml"] = app.GetPropertyValue("userbottomhtml");
		}
	}
}
